﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SM2TestRunner;
using Utilities;

namespace SM2
{
    public partial class SM2_CONTROL_BOARD : Form
    {
        private int i = 0;
        private int intTestCaseOrder = 1;
        private DataTable DT_TESTSUITE = new DataTable();
        private TestStep TESTSTEP;
        private TestCase TESTCASE;
        private TestSuite TESTSUITE = new TestSuite();
        private string strTempTestSuiteFilename = "";


        public SM2_CONTROL_BOARD()
        {
            InitializeComponent();   
        }

        private void btnDemo_Click(object sender, EventArgs e)
        {
            //Step 1. BUILD TESTSUITE
            TestSuite tsItem = TESTSUITE;
            tsItem.setTestSuiteBROWSER(comboBoxBrowser.SelectedValue.ToString());
            tsItem.setTestSuiteSERVER(comboBoxServers.SelectedValue.ToString());

            //Step 2. RUN TESTSUITE BY TESTRUNNER      
            ExecuteTestSuite(tsItem);

            //Step 3. END LOGGER, END REPORT, SEND REPORT & MAIL & CLOSE
            Utilities.GlobalObject.LOGGER.endLogger();
            Utilities.GlobalObject.REPORT.endReport();
            Utilities.MailUtil.sendMail();

            CleanUp();            
        }

        private void SM2_CONTROL_BOARD_Load(object sender, EventArgs e)
        {
            this.Show();
            this.BringToFront();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
            //Step 1. Start LOGGER, Load SM2_REPOSITORY folder
            Utilities.GlobalObject.LOGGER = new Logger();

            //Step 2. Set all repository config variables and folders and all files
            SM2.Loader.LoadREPOSITORY();

            //Step3. Load default settings
            SetDefaultSetting();

            //Step 4. Start logger, report, mail
            Utilities.GlobalObject.REPORT = new Report();
            Utilities.GlobalObject.MAIL = new Mail(Utilities.GlobalConfig.STR_EMAIL_SERVER);


            string strAutoRun = Repository.SchedulerUtil.getAutoRun();
            if (strAutoRun.Trim().ToLower().Equals("yes"))
            {
                if (!confirm(sender, e))
                {
                    #region If confirm NO confim() = false --> run auto

                    //Step 2. BUILD TESTSUITE FROM DATATABLE
                    TestSuite tsItem = Repository.TestSuiteUtil.getTestSuiteFromFile(Utilities.GlobalFolder.REPOSITORY_TESTSUITE + Repository.SchedulerUtil.getTestsuite() + ".csv");

                    //Step 3. RUN TESTSUITE BY TESTRUNNER
                    ExecuteTestSuite(tsItem);

                    //Step 4. END LOGGER, END REPORT, SEND REPORT & MAIL & CLOSE
                    Utilities.GlobalObject.LOGGER.endLogger();
                    Utilities.GlobalObject.REPORT.endReport();
                    Utilities.GlobalObject.MAIL.send();

                    //Close
                    CleanUp();
                    #endregion
                }
            }       
        }

        private void CleanUp()
        {
            if (!strTempTestSuiteFilename.Equals(""))
            {
                Utilities.FileUtil.deleteFile(strTempTestSuiteFilename);
            }
            this.Close();
        }

        private void ExecuteTestSuite(TestSuite tsItem)
        {
            if (tsItem.getTestSuiteBROWSER().Equals("All"))
            {
                //Save tsItem into file
                strTempTestSuiteFilename = Utilities.GlobalFolder.REPOSITORY_TESTDATA + Utilities.StringUtil.getTime() +".csv";
                Repository.TestSuiteUtil.saveTestSuite2File(tsItem, strTempTestSuiteFilename);

                //Loop over all browser in datatable to run
                for (int i = 0; i < Utilities.GlobalRunning.DataTableBrowsers.Rows.Count; i++)
                {
                    DataRow DR = Utilities.GlobalRunning.DataTableBrowsers.Rows[i];
                    string strBrowser = DR[0].ToString();

                    if (!strBrowser.Equals("All"))
                    {
                        //Build TESTSUITE
                        TestSuite TESTSUITE = Repository.TestSuiteUtil.getTestSuiteFromFile(strTempTestSuiteFilename); 

                        //Build Type of Browser
                        Utilities.GlobalRunning.strBROWSER = strBrowser;

                        //Run
                        TestRunner TEST_ENGINE = new TestRunner();
                        TEST_ENGINE.run(TESTSUITE);
                    }
                }
            }
            else
            {
                Utilities.GlobalRunning.strBROWSER = tsItem.getTestSuiteBROWSER();
                TestRunner TEST_ENGINE = new TestRunner();
                TEST_ENGINE.run(tsItem);
            }
        }

        private void SetDefaultSetting()
        {
            //Label
            labelSM2REPOSITORYDIRECTORYPATH.Text = Utilities.GlobalFolder.REPOSITORY;

            //Owners
            listBoxOwners.DisplayMember = "Attribute2";
            listBoxOwners.ValueMember = "Attribute1"; 
            try
            {
                listBoxOwners.DataSource = Repository.MappingUtil.buildOwnersDataTable();
            }
            catch (Exception ex)
            {
                Utilities.GlobalObject.LOGGER.log("Failed to load CheckedListBox Owners Utilities.MappingUtil.buildOwners()");
                Utilities.GlobalObject.LOGGER.log(ex.ToString());
            }

            //Browsers
            comboBoxBrowser.DisplayMember = "Attribute2";
            comboBoxBrowser.ValueMember = "Attribute1";
            try
            {
                Utilities.GlobalRunning.DataTableBrowsers = Repository.ConfigUtil.buildBrowserTypesDataTable();
                comboBoxBrowser.DataSource = Repository.ConfigUtil.buildBrowserTypesDataTable();
            }
            catch (Exception ex)
            {
                Utilities.GlobalObject.LOGGER.log("Failed to load ComboBox Browser Repository.ConfigUtil.buildBrowserTypesDataTable()");
                Utilities.GlobalObject.LOGGER.log(ex.ToString());
            }

            //Servers
            comboBoxServers.DisplayMember = "Attribute2";
            comboBoxServers.ValueMember = "Attribute1";
            try
            {
                comboBoxServers.DataSource = Repository.ConfigUtil.buildServersTypesDataTable();
            }
            catch (Exception ex)
            {
                Utilities.GlobalObject.LOGGER.log("Failed to load ComboBox Servers Repository.ConfigUtil.buildServersTypesDataTable()");
                Utilities.GlobalObject.LOGGER.log(ex.ToString());
            }

            //DataTable for TestSuite
            DT_TESTSUITE.Columns.Add(new DataColumn("Case#", typeof(string)));
            DT_TESTSUITE.Columns.Add(new DataColumn("Detail testcase", typeof(string)));

            comboBoxTestSuite.DisplayMember = "FileName";
            comboBoxTestSuite.ValueMember = "FileName";
            try
            {
                comboBoxTestSuite.DataSource = Repository.TestSuiteUtil.buildTestSuiteList();
            }
            catch (Exception ex)
            {
                Utilities.GlobalObject.LOGGER.log("Failed to load ComboBox TestSuite Utilities.GlobalInit.buildTestSuiteDataTable()");
                Utilities.GlobalObject.LOGGER.log(ex.ToString());
            }

            //Scheduler
            string strAutoRun = Repository.SchedulerUtil.getAutoRun();
            if (strAutoRun.Trim().ToLower().Equals("no"))
            {
                btnScheduler.Text = "OFF";
                btnScheduler.ForeColor = Color.Blue;
            }
            else
            {
                btnScheduler.Text = "ON";
                btnScheduler.ForeColor = Color.Green;
            }
        }

        private Boolean confirm(object sender, System.EventArgs e)
        {
            DialogResult x = Popups.ConfirmAutoClose.ShowConfirmationDialog(
                "Confirm stop auto run",
                "Would you like to stop \"auto run\"?", 5);

            if (x == DialogResult.Yes)
            {
                //Set autorun = no
                string strAUTORUN = "no";
                Repository.SchedulerUtil.setAUTORUN(strAUTORUN);
                return true;
            }
            else return false;
        }

        private void listBoxOwners_SelectedIndexChanged(object sender, EventArgs e)
        {
            string strSelectedOwner = listBoxOwners.SelectedValue.ToString();
            if (!strSelectedOwner.Equals(""))
            {
                listBoxTestObjects.ValueMember = "Attribute1";
                listBoxTestObjects.DisplayMember = "Attribute2";
                try
                {
                    listBoxTestObjects.DataSource = Repository.MappingUtil.buildObjectsDataTable(strSelectedOwner);
                }
                catch (Exception ex)
                {
                    Utilities.GlobalObject.LOGGER.log("Failed to load Listbox Objects Utilities.GlobalInit.buildObjectsDataTable()");
                    Utilities.GlobalObject.LOGGER.log(ex.ToString());
                }
            }
        }

        private void listBoxTestObjects_SelectedIndexChanged(object sender, EventArgs e)
        {
            string strSelectedObject = listBoxTestObjects.SelectedValue.ToString();
            if (!strSelectedObject.Equals(""))
            {
                listBoxTestActions.ValueMember = "Attribute1";
                listBoxTestActions.DisplayMember = "Attribute2";
                try
                {
                    listBoxTestActions.DataSource = Repository.MappingUtil.buildActionsDataTable(strSelectedObject);
                }
                catch (Exception ex)
                {
                    Utilities.GlobalObject.LOGGER.log("Failed to load Listbox Actions Utilities.GlobalInit.buildActionsDataTable()");
                    Utilities.GlobalObject.LOGGER.log(ex.ToString());
                }
            }
        }

        private void btnAddTestStep_Click(object sender, EventArgs e)
        {
            string strOwner = listBoxOwners.SelectedValue.ToString();
            string strObject = listBoxTestObjects.SelectedValue.ToString();
            string strAction = listBoxTestActions.SelectedValue.ToString();

            //Start TESTSTEP, TESTCASE
            TESTSTEP = new TestStep();
            if (i == 0) TESTCASE = new TestCase();

            //Build Teststep item
            TESTSTEP.setOwner(strOwner);
            TESTSTEP.setObjectName(strObject);
            TESTSTEP.setAction(strAction);
            TESTSTEP.setParameters(Popups.InputDispatcher.TEST_PARAMETER);
            TESTSTEP.setValidation(Popups.InputDispatcher.strValidationTextPresents);

            //Add Teststep into Testcase item
            TESTCASE.addTestStep(TESTSTEP);

            //For display
            string strTestStep = strAction;
            if (i++ > 0) strTestStep = "->" + strTestStep;
            richTextBoxTestCase.Text = richTextBoxTestCase.Text + strTestStep;

            //Reset InputDispatcher
            Popups.InputDispatcher.TEST_PARAMETER = new SM2TestRunner.TestParameters();
            Popups.InputDispatcher.strValidationTextPresents = "";

            //Reset Listbox Owner
            listBoxOwners.SetSelected(0, true);

            //Clear Objects and Actions Listboxes
            DataTable dtBLANK = new DataTable();
            dtBLANK.Columns.Add(new DataColumn("Attribute1", typeof(string)));
            dtBLANK.Columns.Add(new DataColumn("Attribute2", typeof(string)));
            listBoxTestObjects.DataSource = dtBLANK;
            listBoxTestActions.DataSource = dtBLANK;
        }

        private void btnAddTestCase_Click(object sender, EventArgs e)
        {
            //Add TESTCASE into TESTSUITE
            TESTSUITE.addTestCase(TESTCASE);

            //Update Grid View testsuite
            DataRow DR = DT_TESTSUITE.NewRow();
            DR[0] = intTestCaseOrder++;
            DR[1] = richTextBoxTestCase.Text;

            DT_TESTSUITE.Rows.Add(DR);

            dataGridViewTestSuite.DataSource = DT_TESTSUITE;
            richTextBoxTestCase.Text = "";
            i = 0;
        }

        private void btnSaveTestSuite_Click(object sender, EventArgs e)
        {
            //Prompt for name of test suite and save
            Popups.PromptInput SAVETESTSUITE = new Popups.PromptInput();
            SAVETESTSUITE.ShowInputDialog();
            string strTS = Popups.InputDispatcher.strTS;

            //Save selected BROWSER & SERVER into tsItem
            TESTSUITE.setTestSuiteBROWSER(comboBoxBrowser.SelectedValue.ToString());
            TESTSUITE.setTestSuiteSERVER(comboBoxServers.SelectedValue.ToString());

            //Save tsItem to file and re-load combox testsuites
            try
            {
                Repository.TestSuiteUtil.saveTestSuite2File(TESTSUITE, Utilities.GlobalFolder.REPOSITORY_TESTSUITE + strTS + ".csv");
                comboBoxTestSuite.DataSource = Repository.TestSuiteUtil.buildTestSuiteList();
            }
            catch (Exception ex)
            {
                Utilities.GlobalObject.LOGGER.log("Failed to save & reload ComboBox TestSuite Utilities.DataTableUtil.saveDataTable2File() & Utilities.GlobalInit.buildTestSuiteDataTable()");
                Utilities.GlobalObject.LOGGER.log(ex.ToString());
            }
            
            //Clear datagrid test suite            
            DT_TESTSUITE.Clear();
            dataGridViewTestSuite.DataSource = DT_TESTSUITE;
        }

        private void btnRemoveTestSuite_Click(object sender, EventArgs e)
        {
            string strSelectedTS = comboBoxTestSuite.SelectedValue.ToString();
            string strFile = Utilities.GlobalFolder.REPOSITORY_TESTSUITE + strSelectedTS + ".csv";
            Utilities.FileUtil.deleteFile(strFile);
            try
            {
                comboBoxTestSuite.DataSource = Repository.TestSuiteUtil.buildTestSuiteList();
            }
            catch (Exception ex)
            {
                Utilities.GlobalObject.LOGGER.log("Failed to load ComboBox TestSuite Utilities.GlobalInit.buildTestSuiteDataTable()");
                Utilities.GlobalObject.LOGGER.log(ex.ToString());
            }
            comboBoxTestSuite.Refresh();
        }

        private void btnLoadTestSuite_Click(object sender, EventArgs e)
        {
            string strSelectedTS = comboBoxTestSuite.SelectedValue.ToString();
            string strFile = Utilities.GlobalFolder.REPOSITORY_TESTSUITE + strSelectedTS + ".csv";
            DT_TESTSUITE.Clear();
          
            //Build TESTSUITE
            TESTSUITE = Repository.TestSuiteUtil.getTestSuiteFromFile(strFile);  

            //Get Server & Browser 
            comboBoxBrowser.SelectedValue = TESTSUITE.getTestSuiteBROWSER();
            comboBoxServers.SelectedValue = TESTSUITE.getTestSuiteSERVER();

            //Load DT_TESTSUITE into Grid
            DT_TESTSUITE = Repository.TestSuiteUtil.getTestSuiteDataTableGridViewFromFile(strFile);  
            dataGridViewTestSuite.DataSource = DT_TESTSUITE;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            //Clear TESTSUITE
            TESTSUITE = new TestSuite();

            //Clear datagrid test suite
            DT_TESTSUITE.Clear();
            dataGridViewTestSuite.DataSource = DT_TESTSUITE;
        }

        private void btnClearTestCase_Click(object sender, EventArgs e)
        {
            //Newly created TestStep will be the first step in testcase
            i = 0;

            //Update rickTextbox view
            richTextBoxTestCase.Text = "";
        }

        private void btnScheduler_Click(object sender, EventArgs e)
        {
            Popups.Scheduler SCHEDULER = new Popups.Scheduler();
            SCHEDULER.ShowInputDialog();

            //Scheduler
            string strAutoRun = Repository.SchedulerUtil.getAutoRun();
            if (strAutoRun.Trim().ToLower().Equals("no"))
            {
                btnScheduler.Text = "OFF";
                btnScheduler.ForeColor = Color.Blue;
            }
            else
            {
                btnScheduler.Text = "ON";
                btnScheduler.ForeColor = Color.Green;
            }
        }

        private void listBoxTestActions_SelectedIndexChanged(object sender, EventArgs e)
        {
            string strlistBoxTestActions = listBoxTestActions.SelectedValue.ToString();

            #region Login

            switch (strlistBoxTestActions)
            {
                case "loginValidate":
                    try
                    {
                        Popups.LoginInputs.ShowLoginInputs();
                        if (Popups.InputDispatcher.TEST_PARAMETER.isSet()) btnAddTestStep_Click(sender, e);
                    }
                    catch (Exception ex)
                    {
                        Utilities.GlobalObject.LOGGER.log("Failed to load Popup ShowLoginInputs");
                        Utilities.GlobalObject.LOGGER.log(ex.ToString());
                    }
                    break;

                default:
                    break;
            }

            #endregion

            #region Dashboard

            switch (strlistBoxTestActions)
            {
                case "createDashBoard":
                    try
                    {
                        Popups.DashboardInputs.ShowDashboardCreationInputs("createDashBoard");
                        if (Popups.InputDispatcher.TEST_PARAMETER.isSet()) btnAddTestStep_Click(sender, e);
                    }
                    catch (Exception ex)
                    {
                        Utilities.GlobalObject.LOGGER.log("Failed to load Popup DashboardInputs");
                        Utilities.GlobalObject.LOGGER.log(ex.ToString());
                    }
                    break;
                case "removeDashBoard":
                    try
                    {
                        Popups.DashboardInputs.ShowDashboardCreationInputs("removeDashBoard");
                        if (Popups.InputDispatcher.TEST_PARAMETER.isSet()) btnAddTestStep_Click(sender, e);
                    }
                    catch (Exception ex)
                    {
                        Utilities.GlobalObject.LOGGER.log("Failed to load Popup DashboardInputs");
                        Utilities.GlobalObject.LOGGER.log(ex.ToString());
                    }
                    break;
                case "editDashBoard":
                    try
                    {
                        Popups.DashboardInputs.ShowDashboardCreationInputs("editDashBoard");
                        if (Popups.InputDispatcher.TEST_PARAMETER.isSet()) btnAddTestStep_Click(sender, e);
                    }
                    catch (Exception ex)
                    {
                        Utilities.GlobalObject.LOGGER.log("Failed to load Popup DashboardInputs");
                        Utilities.GlobalObject.LOGGER.log(ex.ToString());
                    }
                    break;
                
                default:
                    break;
            }

            #endregion

            #region Panel
            switch (strlistBoxTestActions)
            {
                case "addPanel":
                    try
                    {
                        Popups.DashboardInputs.ShowDashboardCreationInputs("addPanelToDashboard");
                        if (Popups.InputDispatcher.TEST_PARAMETER.isSet()) btnAddTestStep_Click(sender, e);
                    }
                    catch (Exception ex)
                    {
                        Utilities.GlobalObject.LOGGER.log("Failed to load Popup DashboardInputs");
                        Utilities.GlobalObject.LOGGER.log(ex.ToString());
                    }
                    break;
                case "editPanel":
                    try
                    {
                        Popups.EditPanel.ShowEditPanel();
                        if (Popups.InputDispatcher.TEST_PARAMETER.isSet()) btnAddTestStep_Click(sender, e);
                    }
                    catch (Exception ex)
                    {
                        Utilities.GlobalObject.LOGGER.log("Failed to load Popup PanelInputs");
                        Utilities.GlobalObject.LOGGER.log(ex.ToString());
                    }
                    break;
                default:
                    break;
            }

            #endregion

            #region Profile

            switch (strlistBoxTestActions)
            {
                case "createNewProfile":
                    try
                    {
                        Popups.ProfileInput.ShowProfileInput("createNewProfile");
                        if (Popups.InputDispatcher.TEST_PARAMETER.isSet()) btnAddTestStep_Click(sender, e);
                    }
                    catch (Exception ex)
                    {
                        Utilities.GlobalObject.LOGGER.log("Failed to load Popup Profile");
                        Utilities.GlobalObject.LOGGER.log(ex.ToString());
                    }
                    break;
                case "deleteProfile":
                    try
                    {
                        Popups.ProfileInput.ShowProfileInput("deleteProfile");
                        if (Popups.InputDispatcher.TEST_PARAMETER.isSet()) btnAddTestStep_Click(sender, e);
                    }
                    catch (Exception ex)
                    {
                        Utilities.GlobalObject.LOGGER.log("Failed to load Popup Profile");
                        Utilities.GlobalObject.LOGGER.log(ex.ToString());
                    }
                    break;
                case "openProfile":
                    try
                    {
                        Popups.ProfileInput.ShowProfileInput("openProfile");
                        if (Popups.InputDispatcher.TEST_PARAMETER.isSet()) btnAddTestStep_Click(sender, e);
                    }
                    catch (Exception ex)
                    {
                        Utilities.GlobalObject.LOGGER.log("Failed to load Popup Profile");
                        Utilities.GlobalObject.LOGGER.log(ex.ToString());
                    }
                    break;
                case "renameProfile":
                    try
                    {
                        Popups.ProfileInput.ShowProfileInput("renameProfile");
                        if (Popups.InputDispatcher.TEST_PARAMETER.isSet()) btnAddTestStep_Click(sender, e);
                    }
                    catch (Exception ex)
                    {
                        Utilities.GlobalObject.LOGGER.log("Failed to load Popup Profile");
                        Utilities.GlobalObject.LOGGER.log(ex.ToString());
                    }
                    break;
                case "copyProfile":
                    try
                    {
                        Popups.ProfileInput.ShowProfileInput("copyProfile");
                        if (Popups.InputDispatcher.TEST_PARAMETER.isSet()) btnAddTestStep_Click(sender, e);
                    }
                    catch (Exception ex)
                    {
                        Utilities.GlobalObject.LOGGER.log("Failed to load Popup Profile");
                        Utilities.GlobalObject.LOGGER.log(ex.ToString());
                    }
                    break;
                default:
                    break;
            }

            #endregion

            #region Search Setup

            switch (strlistBoxTestActions)
            {
                case "NewSearchManualEntry":
                case "NewSearchQueryBuilder":
                case "NewSearchBulkUpload":
                    try
                    {
                        Popups.SearchSetup.ShowSearchSetup("New");
                        if (Popups.InputDispatcher.TEST_PARAMETER.isSet()) btnAddTestStep_Click(sender, e);
                    }
                    catch (Exception ex)
                    {
                        Utilities.GlobalObject.LOGGER.log("Failed to load Popup Profile");
                        Utilities.GlobalObject.LOGGER.log(ex.ToString());
                    }
                    break;
                default:
                    break;
            }

            #endregion

            #region Theme Graph

            switch (strlistBoxTestActions)
            {
                case "createThemeGraph":
                    try
                    {
                        Popups.ThemeInputs.ShowThemeInputs("createThemeGraph");
                        if (Popups.InputDispatcher.TEST_PARAMETER.isSet()) btnAddTestStep_Click(sender, e);
                    }
                    catch (Exception ex)
                    {
                        Utilities.GlobalObject.LOGGER.log("Failed to load Popup Theme Graph");
                        Utilities.GlobalObject.LOGGER.log(ex.ToString());
                    }
                    break;

                default:
                    break;
            }

            #endregion

            #region Generate Report

            switch (strlistBoxTestActions)
            {
                case "GenerateReportDashboard":
                    try
                    {
                        Popups.GenerateReportInputs.ShowGenerateReportInputs("GenerateReportDashboard");
                        if (Popups.InputDispatcher.TEST_PARAMETER.isSet()) btnAddTestStep_Click(sender, e);
                    }
                    catch (Exception ex)
                    {
                        Utilities.GlobalObject.LOGGER.log("Failed to load Popup Generate Report");
                        Utilities.GlobalObject.LOGGER.log(ex.ToString());
                    }
                    break;

                default:
                    break;
            }

            #endregion
        }

        private void buttonExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnUpdateSM2REPOSITORY_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbDlg = new FolderBrowserDialog();
            if (fbDlg.ShowDialog() == DialogResult.OK)
            {
                string folderName = fbDlg.SelectedPath;
                Utilities.GlobalFolder.REPOSITORY = folderName + "\\";
                SM2.Properties.Settings.Default.SM2_REPOSITORY = Utilities.GlobalFolder.REPOSITORY;
                SM2.Properties.Settings.Default.Save();
            }

            this.Close();
        }

        private void comboBoxServers_SelectedIndexChanged(object sender, EventArgs e)
        {
            Utilities.GlobalRunning.strSERVER_BeingChosen = comboBoxServers.SelectedValue.ToString();
        }
    }
}
